package com.fancy.learncenter.ui.fragment;


import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Canvas;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.andview.refreshview.XRefreshView;
import com.facebook.drawee.view.SimpleDraweeView;
import com.fancy.learncenter.R;
import com.fancy.learncenter.bean.BaseBean;
import com.fancy.learncenter.bean.BookStoreDataBean;
import com.fancy.learncenter.common.Constant;
import com.fancy.learncenter.net.CustomNetCallBack;
import com.fancy.learncenter.net.CustomNetSubscriber;
import com.fancy.learncenter.net.HttpMehtod;
import com.fancy.learncenter.ui.activity.MySchoolActivity;
import com.fancy.learncenter.ui.activity.ScanActivity;
import com.fancy.learncenter.ui.activity.SearchActivity;
import com.fancy.learncenter.ui.activity.base.MallCommonH5Activity;
import com.fancy.learncenter.ui.adapter.FragmentBookStoreRVAdapter;
import com.fancy.learncenter.ui.adapter.FragmentBoosStoreBookCategoryAdapter;
import com.fancy.learncenter.ui.adapter.FragmentBoosStoreEdenAdapter;
import com.fancy.learncenter.ui.view.CustomFootView;
import com.fancy.learncenter.ui.view.CustomHeaderView;
import com.fancy.learncenter.ui.view.TopBanner;
import com.fancy.learncenter.utils.LogUtil;
import com.fancy.learncenter.utils.NetUtil;
import com.fancy.learncenter.utils.PermissionHelper;
import com.fancy.learncenter.utils.Utils;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * 书店
 */
public class BookStoreFragment extends Fragment {
    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;

    @Bind(R.id.scan_img)
    ImageView scanImg;

    View view;
    LinearLayout topLL;
    @Bind(R.id.xRefreshView)
    XRefreshView xRefreshView;

    private RecyclerView selectBookRecylerView;
    private RecyclerView edenRecylerView;
    private LayoutInflater inflater;
    private List<View> vpView;
    private LinearLayout topBanner;
    private LinearLayout bookStoreLayout;
    private List<BookStoreDataBean.GoodsListBean> recycleViewData;
    private FragmentBookStoreRVAdapter recycleViewAdapter;

    private List<BookStoreDataBean.GardenEnjoyBean> edenData;
    private FragmentBoosStoreEdenAdapter edenAdapter;

    private List<BookStoreDataBean.BookCategoryBean> bookCategoryData;
    private FragmentBoosStoreBookCategoryAdapter bookCategoryAdapter;


//    PermissionHelper mHelper;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_book_store, container, false);
        ButterKnife.bind(this, view);
        topBanner = (LinearLayout) inflater.inflate(R.layout.fragment_bookstore_banner, null);
        this.inflater = inflater;

        initBanner();
        initEden();
        initBookCategory();
        initRecycleView();
        getData(false);

        return view;
    }

    TopBanner viewPager;
    List<BookStoreDataBean.BannerBeanX> bannerDatas;

    private void initBanner() {
        topLL = (LinearLayout) topBanner.findViewById(R.id.top_LL);
        viewPager = (TopBanner) topBanner.findViewById(R.id.banner);

        bannerDatas = new ArrayList<>();


        viewPager.setBindViewCallBack(new TopBanner.BindViewCallBack<BookStoreDataBean.BannerBeanX>() {
            @Override
            public void bindView(View rootView, final int position, final BookStoreDataBean.BannerBeanX itemData) {
                SimpleDraweeView simpleDraweeView = (SimpleDraweeView) rootView.findViewById(R.id.simpleDraweeView);
                simpleDraweeView.setImageURI(itemData.getImg());

                rootView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(getActivity(), MallCommonH5Activity.class);
                        intent.putExtra(MallCommonH5Activity.URL_KEY, itemData.getLink() + "");
                        startActivity(intent);
                    }
                });
            }
        });
    }

    private void initEden() {
        edenData = new ArrayList<>();
        edenRecylerView = (RecyclerView) topBanner.findViewById(R.id.eden);
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        edenRecylerView.setLayoutManager(manager);
        edenAdapter = new FragmentBoosStoreEdenAdapter(getActivity(), edenData);
        edenRecylerView.setAdapter(edenAdapter);
    }


    private void initBookCategory() {
        bookCategoryData = new ArrayList();
        selectBookRecylerView = (RecyclerView) topBanner.findViewById(R.id.select_book);
        bookStoreLayout = (LinearLayout) topBanner.findViewById(R.id.book_store_layout);
        LinearLayoutManager manager2 = new LinearLayoutManager(getActivity());
        manager2.setOrientation(LinearLayoutManager.HORIZONTAL);
//        selectBookRecylerView.setLayoutManager(manager2);

        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 5);
        gridLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        selectBookRecylerView.setLayoutManager(gridLayoutManager);
        selectBookRecylerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
                super.onDraw(c, parent, state);
            }
        });
        bookCategoryAdapter = new FragmentBoosStoreBookCategoryAdapter(getActivity(), bookCategoryData);
        selectBookRecylerView.setAdapter(bookCategoryAdapter);
    }


    private void initRecycleView() {
        recycleViewData = new ArrayList<>();

        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);

        recycleViewAdapter = new FragmentBookStoreRVAdapter(getActivity(), recycleViewData);
        recyclerView.setAdapter(recycleViewAdapter);

        recycleViewAdapter.setHeaderView(topBanner, recyclerView);
        xRefreshView.setCustomHeaderView(new CustomHeaderView(getActivity()));
        xRefreshView.setPinnedTime(1000);
        xRefreshView.setMoveForHorizontal(true);
        xRefreshView.setXRefreshViewListener(new XRefreshView.XRefreshViewListener() {
            @Override
            public void onRefresh() {
                getData(true);
            }

            @Override
            public void onRefresh(boolean isPullDown) {

            }

            @Override
            public void onLoadMore(boolean isSilence) {

            }

            @Override
            public void onRelease(float direction) {

            }

            @Override
            public void onHeaderMove(double headerMovePercent, int offsetY) {

            }
        });
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);

        if (hidden) {
            viewPager.stopAutoPlay();
        } else {
            viewPager.startAutoPlay();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.scan_img, R.id.search_et, R.id.shop_cart})
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.scan_img:
                intent = new Intent(getActivity(), ScanActivity.class);
                getActivity().startActivity(intent);
                break;
            case R.id.search_et:
                intent = new Intent(getActivity(), SearchActivity.class);
                getActivity().startActivity(intent);
                break;
            case R.id.shop_cart: //购物车
                intent = new Intent(getActivity(), MallCommonH5Activity.class);
                intent.putExtra(MallCommonH5Activity.URL_KEY, Constant.getMallShopCart());
                getActivity().startActivity(intent);
                break;
        }
    }


    private void getData(final boolean refresh) {
        HttpMehtod.getInstance().getHomeBookStore(new CustomNetSubscriber(getActivity()) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {
                //解析数据
                BaseBean<BookStoreDataBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), BookStoreDataBean.class);
                //数据业务逻辑处理
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<BookStoreDataBean>() {
                    @Override
                    public void success(BookStoreDataBean dataBean) {
                        bookCategoryData.removeAll(bookCategoryData);
                        edenData.removeAll(edenData);
                        recycleViewData.removeAll(recycleViewData);

                        bookCategoryData.addAll(dataBean.getBookCategory());
                        edenData.addAll(dataBean.getGardenEnjoy());
                        recycleViewData.addAll(dataBean.getGoodsList());

                        if (bookCategoryData != null && bookCategoryData.size() == 0) {
                            selectBookRecylerView.setVisibility(View.GONE);
                            bookStoreLayout.setVisibility(View.GONE);
                        } else {
                            selectBookRecylerView.setVisibility(View.VISIBLE);
                            bookStoreLayout.setVisibility(View.VISIBLE);
                        }

                        if (!refresh) {
                            bannerDatas.addAll(dataBean.getBanner());
                            viewPager.setResData(bannerDatas, R.layout.fragment_bookstore_vp_item);

                        } else {
                            xRefreshView.stopRefresh();
                        }

                    }

                    @Override
                    public void fail(String errorCode) {

                    }

                }).dealData();
            }

            @Override
            public void onCompleted() {
                super.onCompleted();

                bookCategoryAdapter.notifyDataSetChanged();
                edenAdapter.notifyDataSetChanged();
                recycleViewAdapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        mHelper.handleRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}
